<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" :title="title" @ok="handleSubmit" width="700px">
    <!-- <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ title }} </span>
    </template> -->
    <BasicForm @register="registerForm" >
      <template #domain="{ model, field }">
        <a-input v-model:value="model[field]" :addon-before="tenantConfig.domainProtocol"  :addon-after="tenantConfig.firstLevelDomain" />
      </template>

      <template #userName="{ model, field }">
        <template v-if="!model['id']">
          <a-input v-model:value="model[field]" readOnly placeholder="用户账号" @click="handleSelectUser"/>
        </template>
        <template v-else>
          <a-input v-model:value="model[field]" readOnly placeholder="用户账号" />
        </template>
      </template>
    </BasicForm>
  </BasicDrawer>
  <!--用户选择弹窗-->
  <SelectUserJoin @register="registerAddUserModal" @select="submitSelectedUser"/>
</template>
<script lang="ts" setup>
import { ref, computed, unref } from 'vue';
import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
import { useModal } from '/@/components/Modal';
import SelectUserJoin from '/@/views/system/tenantMember/SelectUserJoin.vue';
import { BasicForm, useForm } from '/@/components/Form/index';
import { formSchema } from './tenant.data';
import { saveOrUpdateTenant, getTenant, getPlatformConfig } from '/@/api/sys/tenant';
import { PlatformConfig } from './tenant.model';
import { useMessage } from '/@/hooks/web/useMessage';
import { listScene } from '/@/api/sys/scene';
import { listTenantPackage } from "./package/api"
import { useUserStore } from '/@/store/modules/user';
import { TenantType } from '/@/enums/bizEnum'

const userStore = useUserStore()
const selectTenant = userStore.getSelectTenant
const isSysAdminTenant = userStore.getIsSysAdminTenant
const { createMessage } = useMessage();
// 声明Emits
const emit = defineEmits(['success', 'register']);

const isUpdate = ref(true);
const tenantConfig = ref<PlatformConfig>({})
const selectdUser = ref<any>({})
const packageList = ref<any[]>([])
const [registerAddUserModal, {openModal: openAddUserModal}] = useModal();

const wrapperCol: Partial<ColEx> = {
  xs: 24, // <576px
  sm: 24, // ≥576px
  md: 24, // ≥768px
  lg: 24, // ≥992px
  xl: 24, // ≥1200px
  xxl: 24, // ≥1600px
}

//表单配置
const [registerForm, { resetFields, setFieldsValue, validate, updateSchema }] = useForm({
  schemas: formSchema,
  labelWidth: 100,
  showActionButtonGroup: false,
  wrapperCol
});

//表单赋值
const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
  console.timeEnd('open-drawer')
  //重置表单
  await resetFields();
  tenantConfig.value = await getPlatformConfig()
  setDrawerProps({ confirmLoading: false })
  isUpdate.value = !!data?.isUpdate;
  if (selectTenant.tenantType === TenantType.MANAGE) {
    packageList.value = await listTenantPackage({sceneId: selectTenant.sceneId})
    updatePackageIdScheme(TenantType.MAIN, packageList.value)
  } else {
    updateSchema({
      field: 'sceneId',
      component: 'ApiSelect',
      componentProps: ({ formModel, formActionType }) => {
        return {
          optionFilterProp: "label",
          labelField: 'name',
          valueField: 'id',
          showSearch: true,
          api: listScene,
          onSelect: async (value: any, option: any) => {
            formModel.packageId = undefined
            formModel.subPackageId = undefined
            console.log("option", option);
            packageList.value = await listTenantPackage({sceneId: value})
            updatePackageIdScheme(formModel['tenantType'], packageList.value)
          },
          onOptionsChange: async (options) => {
            
          }
        }
      },
    })

    updateSchema({
      field: 'tenantType',
      componentProps: ({ formModel }) => {
        return {
          type: 'radio',
          filter: (item) => {
            return item !== '4'
          },
          dictCode: 'tenant_type',
          onChange: async (value) => {
            formModel.packageId = undefined
            formModel.subPackageId = undefined
            updatePackageIdScheme(value, packageList.value)
          }
        }
      },
    })

  }
  
  if (unref(isUpdate)) {
    //获取详情
    data.record = await getTenant({ id: data.record.id });
    if (userStore.getSelectTenant.tenantType === TenantType.PLATFORM) {
      packageList.value = await listTenantPackage({sceneId: data.record.sceneId})
      updatePackageIdScheme(data.record.tenantType, packageList.value)
    }
  }
  await setFieldsValue({...data.record });

});

const title = computed(() => (!unref(isUpdate) ? '新增租户' : '编辑租户'));

async function handleSubmit(v) {
  try {
    let values = await validate();
    console.log('values', values)
    setDrawerProps({ confirmLoading: true });
    const sceneId = isSysAdminTenant ? values.sceneId : selectTenant.sceneId
    await saveOrUpdateTenant({ ...values, sceneId }, isUpdate.value);
    closeDrawer();
    emit('success');
    createMessage.success(`${title.value}成功`)
  } finally {
    setDrawerProps({ confirmLoading: false });
  }
}

 const updatePackageIdScheme = async (tenantType, packageList) => {
  const options = unref(packageList).map(e => {
    return {key: e.id, label: e.name, value: e.id, tenantType: e.tenantType}
  })
  console.log('updatePackageSelect ==> tenantType: ', tenantType, 'options: ', options)
  updateSchema({
    field: 'packageId',
    required: true,
    component: 'Select',
    componentProps: {
      optionFilterProp: "label",
      placeholder: '请选择主租户套餐',
      showSearch: true,
      options: options.filter(e => e.tenantType === tenantType)
    }
  })
  
  updateSchema({
    field: 'subPackageId',
    required: true,
    component: 'Select',
    componentProps: {
      optionFilterProp: "label",
      placeholder: '请选择子租户套餐',
      showSearch: true,
      options: options.filter(e => e.tenantType === TenantType.SUB)
    }
  })
}

const handleSelectUser = () => {
  openAddUserModal(true, {
    inviteWay: 'fromExistUser',
    selectPlatformUser: true,
    isPlatformUser: true,
    singleSelect: true
  })
}

const submitSelectedUser = async (selectRows) => {
  if (selectRows && selectRows.length >= 1) {
    selectdUser.value = selectRows[0]
    console.log('selectRows', selectRows);
    setFieldsValue({userName: selectdUser.value.userName, adminUserId: selectdUser.value.id})
  }
}

</script>
